﻿namespace Auros.EPiSiteMap.Data
{
    using System;
    using System.Linq;
    using EPiServer.Data.Dynamic;

    [EPiServerDataStore(
    StoreName = "SiteMapConfigDataStore",
    AutomaticallyCreateStore = true,
    AutomaticallyRemapStore = true)]
    public class SiteMapConfig 
    {
        public Guid ID { get; set; }
        
        public bool CreateIndexFile { get; set; }

        public string SitemapIndexFileName { get; set; }

        public static SiteMapConfig GetConfig()
        {
            return GetStore().LoadAll<SiteMapConfig>().FirstOrDefault() ?? new SiteMapConfig();
        }
        
        public static void SaveConfig(SiteMapConfig config)
        {
            var store = GetStore();

            var record = store.LoadAll<SiteMapConfig>().FirstOrDefault(item => item.ID == config.ID);

            if (record != null)
            {
                record.CreateIndexFile = config.CreateIndexFile;
                record.SitemapIndexFileName = config.SitemapIndexFileName;
            }
            else
            {
                record = config;
                record.ID = Guid.NewGuid();
            }

            store.Save(record);
        }

        private static DynamicDataStore GetStore()
        {
            return DynamicDataStoreFactory.Instance.GetStore(typeof(SiteMapConfig)) ?? DynamicDataStoreFactory.Instance.CreateStore(typeof(SiteMapConfig));
        }
    }
}